import pagesJSON from "./pages.json"; //

function ZzRouter() {

  let pages = {};
  pagesJSON.pages.forEach((e) => {
    let path = pages[e.name];
    if (path) {
      console.error(`path name '${e.name}' existed already!`)
    }
    pages[e.name] = `/${e.path}`
  })
  this.pages = pages;
}

let proto = ZzRouter.prototype;

proto.get = function(name) {
  return this.pages[name];
}

proto.formatUrl = function(module, param) {
  let e = module;
  let url = ((e.page && this.get(e.page)) || e.url);
  return `${url}${param||''}`;
}

function formatPathQuery(path, params) {
  if (params) {
    if (typeof params === 'string') {
      path += ('?' + params)
    } else if (typeof params === 'object') {
      let cs = JSON.stringify(params)
      cs = encodeURIComponent(cs)
      path += ('?jpo=' + cs)
    }
  }
  return path;
}

proto.to = function(name, params, callback, redirect) {
  
  var path = this.get(name)
  if (!path) {
    callback && callback(false)
    return console.error(`未发现${name}~`)
  }

  path = formatPathQuery(path, params)

  const opts = {
    url: path,
    success: function() {
      callback && callback(true)
    },
    fail: function() {
      callback && callback(false)
    },
  }

  return redirect ? uni.redirectTo(opts) : uni.navigateTo(opts);
}

proto.reLaunch = function(name, params, callback) {
  var path = this.get(name)
  if (!path) {
    console.error(`未发现${name}~`)
  }

  path = formatPathQuery(path, params)

  return path && uni.reLaunch({
    url: path,
    success: function() {
      callback && callback(true)
    },
    fail: function() {
      callback && callback(false)
    },
  });
}

proto.redirectTo = function(name, params, callback) {
  var path = this.get(name)
  if (!path) {
    console.error(`未发现${name}~`)
  }

  path = formatPathQuery(path, params)

  return path && uni.redirectTo({
    url: path,
    success: function() {
      callback && callback(true)
    },
    fail: function() {
      callback && callback(false)
    },
  });
}

proto.toHome = function(callback) {
  this.reLaunch('home', '', callback)
}

var zzRouter = new ZzRouter();

export default zzRouter;